import { message } from 'antd';
import type { MessageInstance } from 'antd/es/message/interface';

// 存储全局 messageApi
let globalMessageApi: MessageInstance | null = null;

// 初始化 messageApi（在 App 组件顶层调用）
export const initMessage = () => {
  const [messageApi, contextHolder] = message.useMessage();
  globalMessageApi = messageApi;
  return contextHolder;
};

// 封装 success
export const successMsg = (content: string, duration?: number) => {
  if (!globalMessageApi) {
    console.error('messageApi 未初始化，请先调用 initMessage()');
    return;
  }
  globalMessageApi.success({
    content,
    duration: duration || 3,
    className: 'global-message',
  });
};

// 封装 error
export const errorMsg = (content: string, duration?: number) => {
  if (!globalMessageApi) {
    console.error('messageApi 未初始化，请先调用 initMessage()');
    return;
  }
  globalMessageApi.error({
    content,
    duration: duration || 3,
    className: 'global-message-error',
  });
};

// 封装 warning
export const warningMsg = (content: string, duration?: number) => {
  if (!globalMessageApi) {
    console.error('messageApi 未初始化，请先调用 initMessage()');
    return;
  }
  globalMessageApi.warning({
    content,
    duration: duration || 3,
    className: 'global-message-warning',
  });
};

// 封装 info
export const infoMsg = (content: string, duration?: number) => {
  if (!globalMessageApi) {
    console.error('messageApi 未初始化，请先调用 initMessage()');
    return;
  }
  globalMessageApi.info({
    content,
    duration: duration || 3,
    className: 'global-message-info',
  });
};